#include "../common/dispatcher.hpp"
#include "../client/requestor.hpp"
#include "../client/rpc_caller.hpp"
#include <unistd.h>

void callback(const Json::Value &result)
{
    ILOG("callback result: %d", result.asInt());
}

int main()
{
    auto requestor = std::make_shared<bitrpc::client::Requestor>();
    auto caller = std::make_shared<bitrpc::client::RpcCaller>(requestor);

    auto dispather = std::make_shared<bitrpc::Dispatcher>();
    auto rsp_cb = std::bind(&bitrpc::client::Requestor::onResponse, requestor.get(), std::placeholders::_1, std::placeholders::_2);
    dispather->registerHandler<bitrpc::BaseMessage>(bitrpc::MType::RSP_RPC, rsp_cb);

    auto client = bitrpc::ClientFactory::create("127.0.0.1", 9090);
    auto message_cb = std::bind(&bitrpc::Dispatcher::onMessage, dispather.get(), std::placeholders::_1, std::placeholders::_2);
    client->setMessageCallback(message_cb);
    client->connect();

    auto conn = client->connection();
    Json::Value params, result;
    params["num1"] = 11;
    params["num2"] = 22;
    bool ret = caller->call(conn, "Add", params, result);
    if (ret != false)
    {
        std::cout << "result: " << result.asInt() << std::endl;
    }

    bitrpc::client::RpcCaller::JsonAsyncResponse res_future;
    params["num1"] = 33;
    params["num2"] = 44;
    ret = caller->call(conn, "Add", params, res_future);
    if (ret != false)
    {
        result = res_future.get();
        ILOG("result: %d", result.asInt());
    }

    params["num1"] = 55;
    params["num2"] = 66;
    ret = caller->call(conn, "Add", params, callback);

    ILOG("-------\n");

    sleep(10);
    client->shutdown();
    return 0;
}